package com.oriental.manage.controller.specially;

import com.oriental.manage.core.exception.BusiException;
import com.oriental.manage.core.paging.Pagination;
import com.oriental.manage.core.response.ResponseDTO;
import com.oriental.manage.core.utils.BeanUtils;
import com.oriental.manage.core.utils.Validate;
import com.oriental.manage.model.specially.EnterpriseMchntBaseInfo;
import com.oriental.manage.service.specially.EnterpriseMchntBaseInfoService;
import com.oriental.riskfront.api.service.DataDictInterface;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * Created by jinxin on 2017/4/20.
 * 企业商户信息上报
 */
@Controller
@Slf4j
@RequestMapping("specialMerchant/enterpriseMchntInfo")
public class EnterpriseMchntBaseInfoController {

    @Autowired
    EnterpriseMchntBaseInfoService enterpriseMchntBaseInfoService;

    @Autowired
    private DataDictInterface dataDictInterface;

    @RequestMapping("/init")
    public String init(){
        return "specially/searchEnterpriseMchntBaseInfo";
    }

    @RequestMapping("/toUpload")
    public String toUpload(){
        return "specially/uploadEnterpriseMchntBaseInfo";
    }

    @RequestMapping("/toDetail")
    public String toDetail(){
        return "specially/enterpriseMchntBaseInfoDetail";
    }

  @RequestMapping("/toUploadDetail")
    public String toUploadDetail(){
        return "specially/uploadEnterpriseMchntBaseInfoDetail";
    }

    @RequestMapping("/search")
    @ResponseBody
    public ResponseDTO<Pagination<EnterpriseMchntBaseInfo>> search(Pagination<EnterpriseMchntBaseInfo> pagination,EnterpriseMchntBaseInfo enterpriseMchntBaseInfo) {
        ResponseDTO<Pagination<EnterpriseMchntBaseInfo>> responseDTO=new ResponseDTO<>();
        try{
            enterpriseMchntBaseInfoService.search(enterpriseMchntBaseInfo,pagination);
         responseDTO.setSuccess(true);
           responseDTO.setObject(pagination);
        }catch(Exception e){
            log.error("查询失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg("企业商户信息查询失败");
        }
        return responseDTO;
    }


    @RequestMapping("/mchntData")
    @ResponseBody
    protected ResponseDTO<EnterpriseMchntBaseInfo> mchntData(EnterpriseMchntBaseInfo enterpriseMchntBaseInfo) {
        ResponseDTO<EnterpriseMchntBaseInfo> responseDTO = new ResponseDTO<>();
        log.info("编辑上报初始化:{}", enterpriseMchntBaseInfo);
        try {
            enterpriseMchntBaseInfo=enterpriseMchntBaseInfoService.initMchntBaseInfo(enterpriseMchntBaseInfo);
            Map<String, String> map = new TreeMap<String, String>(
                    new Comparator<String>() {
                        public int compare(String obj1, String obj2) {
                            // 升序排序
                            return obj1.compareTo(obj2);
                        }
                    });
           Map<String,String> mapNet= (Map<String,String>)dataDictInterface.getData("CLEARING_NETWORK");
            Map<String,String> mapOpen=(Map<String,String>)dataDictInterface.getData("OPEN_SERVICE_TYPE");
            StringBuilder sb1= new StringBuilder("[");
            map.putAll(mapNet);
            for (Map.Entry<String,String> entry: map.entrySet()
                 ) {
                sb1.append("{id:'").append(entry.getKey()).append("',name:'").append(entry.getValue()).append("'}").append(",");
            }
            sb1.substring(0,sb1.length()-1);
            sb1.append("]");
            map.clear();
            map.putAll(mapOpen);
            StringBuilder sb2= new StringBuilder("[");
            for (Map.Entry<String,String> entry: map.entrySet()
                 ) {
                sb2.append("{id:'").append(entry.getKey()).append("',name:'").append(entry.getValue()).append("'}").append(",");
            }
            sb2.substring(0,sb2.length()-1);
            sb2.append("]");
            enterpriseMchntBaseInfo.setOpenTypeForJS(sb2.toString());
            enterpriseMchntBaseInfo.setNetworkTypeForJS(sb1.toString());
            responseDTO.setSuccess(true);
            responseDTO.setObject(enterpriseMchntBaseInfo);
        } catch (Exception e) {
            log.error("编辑上报初始化失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        }
        return responseDTO;
    }
    @RequestMapping("/uploadDetail")
    @ResponseBody
    protected ResponseDTO<List<EnterpriseMchntBaseInfo>> uploadDetail(EnterpriseMchntBaseInfo enterpriseMchntBaseInfo) {
        ResponseDTO<List<EnterpriseMchntBaseInfo>> responseDTO = new ResponseDTO<>();
        log.info("查看详情:{}", enterpriseMchntBaseInfo);
        try {
            if("0".equals(enterpriseMchntBaseInfo.getNote())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("该商户未编辑上报");
                return responseDTO;
            }
            List<EnterpriseMchntBaseInfo> enterpriseMchntBaseInfoList= enterpriseMchntBaseInfoService.searchForCusCode(enterpriseMchntBaseInfo);
            for (EnterpriseMchntBaseInfo e: enterpriseMchntBaseInfoList
                 ) {
                String openT= e.getOpenType();
                Map<String,String> mapNet= (Map<String,String>)dataDictInterface.getData("CLEARING_NETWORK");
                Map<String,String> mapOpen=(Map<String,String>)dataDictInterface.getData("OPEN_SERVICE_TYPE");
                if(StringUtils.isNotBlank(openT)) {
                    String [] netTypeArr=openT.split(",");
                    StringBuilder netString=new StringBuilder();
                    for (String net : netTypeArr
                            ) {
                        netString.append(mapOpen.get(net)).append(",");
//                        if ("01".equals(net)) {
//                            netString.append("POS").append(",");
//                        }
//                        if ("99".equals(net)) {
//                            netString.append("其他").append(",");
//                        }
//                        if ("02".equals(net)) {
//                            netString.append("条码").append(",");
//                        }
                    }
                    String  s= netString.substring(0,netString.length()-1);
                    e.setOpenType(s);
                }
                String network= e.getNetworkType();
                if(StringUtils.isNotBlank(network)) {
                    String [] netTypeArr=network.split(",");
                    StringBuilder netString=new StringBuilder();
                    for (String net : netTypeArr
                            ) {
                        netString.append(mapNet.get(net)).append(",");
//                        if ("02".equals(net)) {
//                            netString.append("网络支付清算平台").append(",");
//                        }
//                        if ("01".equals(net)) {
//                            netString.append("中国银联").append(",");
//                        }
//                        if ("03".equals(net)) {
//                            netString.append("清算总中心").append(",");
//                        }
//                        if ("04".equals(net)) {
//                            netString.append("农信银").append(",");
//                        }
//                        if ("05".equals(net)) {
//                            netString.append("城商行").append(",");
//                        }
//                        if ("06".equals(net)) {
//                            netString.append("同城结算中心").append(",");
//                        }
//                        if ("99".equals(net)) {
//                            netString.append("其他").append(",");
//                        }
                    }
                    String  s= netString.substring(0,netString.length()-1);
                    e.setNetworkType(s);
                }
                String occ= e.getOccurarea();
                if(StringUtils.isNotBlank(occ)){
                    StringBuilder occString=new StringBuilder();
                    String [] occTypeArr=occ.split(",");
                    List<Map<String, Object>> dataAddress = dataDictInterface.getDataAddress("ADDRESS_Select");
                    Map<String,String> areaMap = new HashMap<>();
                    for (Map<String,Object> m:dataAddress
                            ) {
                        areaMap.put((String)m.get("areaCode"),(String)m.get("areaName"));
                    }
                    for ( String o: occTypeArr
                            ) {
                        occString.append(areaMap.get(o)).append(",");
                    }
                    e.setOccurarea(occString.substring(0,occString.length()-1));
                }
            }
            log.info("详情查看：{}",enterpriseMchntBaseInfoList);
            responseDTO.setSuccess(true);
            responseDTO.setObject(enterpriseMchntBaseInfoList);
        } catch (Exception e) {
            log.error("查看详情失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        }
        return responseDTO;
    }

    @RequestMapping("/upload")
    @ResponseBody
    protected ResponseDTO<String> update(ResponseDTO<String> responseDTO,@RequestBody EnterpriseMchntBaseInfo enterpriseMchntBaseInfo) {
        log.info("修改信息:{}", enterpriseMchntBaseInfo);
        try {
            BeanUtils beanUtils = new BeanUtils();
            Validate.validateObject(enterpriseMchntBaseInfo);
            beanUtils.nullConverNullString(enterpriseMchntBaseInfo);
            log.info("输入参数："+enterpriseMchntBaseInfo);
            Set<String> area= new HashSet<>();
            String [] occ=enterpriseMchntBaseInfo.getOccurarea().split(",");
            for (String  code:occ
            ) {
              area.add(code);
            }
            if(area.size()!=occ.length){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户经营地区范围重复");
                return responseDTO;
            }
//            Map mapMchnt=dataDictInterface.getData("MERCHANT_PROPERTY");
            //根据数据字典的字典项来确定是否必输，如果以后数据字典结构发生重大改变，需要改变此判断项 TODO
            //网络特约商户，必输字段    url  ，serverip ，icp
        if("02".equals(enterpriseMchntBaseInfo.getCusNature())){
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getUrl())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户属性为网络特约商户时 网址必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getServerIp())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户属性为网络特约商户时 服务器IP必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getIcp())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户属性为网络特约商户时 ICP备案编号必输");
                return responseDTO;
            }
            //实体兼网络  Occurarea   OpenType   ChageType   RegAddrProv   RegAddrDetail
        }else if("01".equals(enterpriseMchntBaseInfo.getCusNature())||"03".equals(enterpriseMchntBaseInfo.getCusNature())){
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getOccurarea())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户属性为实体特约商户、实体兼网络特约商户时 商户经营地区范围必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getOpenType())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户属性为实体特约商户、实体兼网络特约商户时 开通业务种类必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getChageType())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户属性为实体特约商户、实体兼网络特约商户时 计费类型必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getRegAddrProv())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户属性为实体特约商户、实体兼网络特约商户时 商户注册地址(省)必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getRegAddrDetail())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户属性为实体特约商户、实体兼网络特约商户时 商户注册地址必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getAddrProv())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户属性为实体特约商户、实体兼网络特约商户时 商户经营地址(省)必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getAddrDetail())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户属性为实体特约商户、实体兼网络特约商户时 商户经营地址必输");
                return responseDTO;
            }
        }
        //在进行判断  01AddrProv   AddrDetail
//        if("01".equals(enterpriseMchntBaseInfo.getCusNature())){
//            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getAddrProv())){
//                responseDTO.setSuccess(false);
//                responseDTO.setMsg("商户属性为实体特约商户时 商户经营地址(省)必输");
//                return responseDTO;
//            }
//            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getAddrDetail())){
//                responseDTO.setSuccess(false);
//                responseDTO.setMsg("商户属性为实体特约商户时 商户经营地址必输");
//                return responseDTO;
//            }
//        }
        if("01".equals(enterpriseMchntBaseInfo.getStatus())){
            if(enterpriseMchntBaseInfo.getStartTime()==null){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户状态为启用时 服务起始时间必输");
                return responseDTO;
            }
        }else  if("03".equals(enterpriseMchntBaseInfo.getStatus())){
            if(enterpriseMchntBaseInfo.getEndTime()==null){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("商户状态为注销时 服务终止时间必输");
                return responseDTO;
            }
        }
        if("02".equals(enterpriseMchntBaseInfo.getExpandType())){

            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getOutServiceName())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("拓展方式为外包服务机构推荐时 外包服务机构名称必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getOutServiceCardType())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("拓展方式为外包服务机构推荐时 外包服务机构法人证件类型必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getOutServiceCardCode())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("拓展方式为外包服务机构推荐时 外包服务机构法人证件号码必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getOutServiceLegCardType())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("拓展方式为外包服务机构推荐时 外包服务机构法定代表人证件类型必输");
                return responseDTO;
            }
            if(StringUtils.isBlank(enterpriseMchntBaseInfo.getOutServiceLegCardCode())){
                responseDTO.setSuccess(false);
                responseDTO.setMsg("拓展方式为外包服务机构推荐时 外包服务机构法定代表人证件号码必输");
                return responseDTO;
            }
        }
            enterpriseMchntBaseInfoService.insertEnterpriseMchntBaseInfo(enterpriseMchntBaseInfo,responseDTO);
        } catch (BusiException e) {
            log.error("参数校验失败", e.getMessage());
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        }catch (Exception e) {
            log.error("更新失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg("更新失败");
        }
        return responseDTO;
    }

}
